define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "UtilDir/loading",
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, SelectOrg, SearchBlock, Loading) {

    var sysPath = getServer() + "/static/app/fxpg/fxEconomicLossProbabilityCompute";

    var fxEconomyLossProbabilityComputeFormHtml = sysPath + "/views/fxEconomicLossProbabilityComputeForm.html";
    var getFxEconomyLossProbabilityComputeController = function () {
        return getServer() + "/fxEconomyLossProbabilityComputes";
    };
    var getFxEconomyLossRiskEvaluateController = function () {
        return getServer() + "/fxEconomyLossRiskEvaluate";
    };

    /**
     * 页面初始化
     */
    var global_K0 = 0, global_K1 = 0;
    var init = function () {
        initSearchBlock();
        queryBtnBind();
        initProvinceSelect("山东省", "日照市", "岚山区");//"山东省", "日照市", "岚山区"  "北京市", "北京市", "海淀区"
    };
    var initProvinceSelect = function (Province, City, Area) {
        var html = "";
        $("#citySelect").append(html);
        $("#areaSelect").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                var ProvinceCode;
                $.each(data, function (idx, item) {
                    if (item.divisionName == Province) {
                        //debugger;
                        ProvinceCode = item.divisionCode;
                        var divisionId = item.divisionId;
                        var htmlCity = '';
                        if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
                            $("#citySelect").append("<option value='" + ProvinceCode + "' exid='" + divisionId + "'>" + Province + "</option>");
                            $('#citySelect').val(ProvinceCode);
                            var htmlArea = '';
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    var AreaCode;
                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == Area) AreaCode = item.divisionCode;
                                        htmlArea += "<option value='" + item.divisionCode + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#areaSelect").append(htmlArea);
                                    $('#areaSelect').val(AreaCode);

                                    createFxEconomyLossProbabilityComputeGrid();
                                }
                            });

                        } else {
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    debugger;
                                    var CityCode;
                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == City) {
                                            CityCode = item.divisionCode;
                                            var divisionId = item.divisionId;
                                            var htmlArea = '';
                                            $.ajax({
                                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                                contentType: "application/json",
                                                type: "get",
                                                success: function (data) {
                                                    var AreaCode;
                                                    $.each(data, function (idx, item) {
                                                        if (item.divisionName == Area) AreaCode = item.divisionCode;
                                                        htmlArea += "<option value='" + item.divisionCode + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                                    });
                                                    $("#areaSelect").append(htmlArea);
                                                    $('#areaSelect').val(AreaCode);
                                                    createFxEconomyLossProbabilityComputeGrid();
                                                }
                                            });
                                        }
                                        htmlCity += "<option value='" + item.divisionCode + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#citySelect").append(htmlCity);
                                    $('#citySelect').val(CityCode);
                                }
                            });
                        }
                    }
                    html += "<option value='" + item.divisionCode + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#provinceSelect").append(html);
                $('#provinceSelect').val(ProvinceCode);
            }
        });
        $("#provinceSelect").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
            $("#citySelect").append(html);
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#citySelect").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionCode + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#citySelect").append(html);
                }
            });
        });
        $("#citySelect").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#areaSelect option").remove();
            $("#areaSelect").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionCode + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#areaSelect").append(html);
                }
            });
        });
    };
    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
    };
    var queryBtnBind = function () {
        $("#btnSearch").click(function () {
            fxEconomyLossProbabilityComputeByArea();
        });
        $("#btnReset").click(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#citySelect option").remove();
			$("#citySelect").append(html);
			$("#areaSelect option").remove();
			$("#areaSelect").append(html);
            initProvinceSelect("北京市", "北京市", "海淀区");
        });
        $("#btnDataSearch").click(function () {
            createFxEconomyLossProbabilityComputeGrid();
        });
    };

    var loading = Loading({text : "正在计算..."});
    var fxEconomyLossProbabilityComputeByArea = function () {
        var province = $("#provinceSelect").val() || "", city = $("#citySelect").val() || "", area = $("#areaSelect").val() || "";
        var formData = {province: province, city: city, area: area};
        loading.show();
        $.ajax({
            url: getFxEconomyLossRiskEvaluateController() + "/computeEconomicLossProbability",
            type: "POST",
            data: formData,
            success: function (result) {
                loading.close();
                console.log(result);
                if (result && result.data) {
                    console.log(result.data);

                } else {
                    $('#fxEconomyLossProbabilityComputeGrid').datagrid('loadData', {total: 0, rows: []});
                    $('#fxEconomyLossProbabilityComputeGrid').datagrid('appendRow', {});
                    var body = $("#fxEconomyLossProbabilityComputeGrid").data().datagrid.dc.body2;
                    var trs = body.find('table tbody').find("tr");
                    while (trs.eq(0).find("td").length > 1) {
                        if (trs.eq(0).find("td").length == 1) break;
                        trs.eq(0).find("td").eq(1).remove();
                    }
                    trs.eq(0).find("td").eq(0).attr("colspan", 6).attr("width", body.width()).css("text-align", "center").html("查询无数据");
                }
            }
        });
    };

    var createFxEconomyLossProbabilityComputeGrid = function () {
        $("#fxEconomyLossProbabilityComputeGrid").datagrid({
            url: getFxEconomyLossProbabilityComputeController() + "/getFxEconomyLossProbabilityComputes",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
            columns: [[
                {
                    field: 'province',
                    title: '省',
                    width: '13%',
                    align: 'center',
                },
                {
                    field: 'city',
                    title: '市',
                    width: '13%',
                    align: 'center',
                },
                {
                    field: 'area',
                    title: '区（县）',
                    width: '13%',
                    align: 'center',
                },
                {
                    field: 'damageDegree',
                    title: '破坏程度',
                    width: '10%',
                    align: 'center',
                    formatter: function (value) {
                        //console.log(arguments[1]);
                        if (value == "0") {
                            return '基本完好';
                        } else if (value == "1") {
                            return '轻微破坏';
                        } else if (value == "2") {
                            return '中等破坏';
                        } else if (value == "3") {
                            return '严重破坏';
                        } else if (value == "4") {
                            return '完全破坏';
                        }
                    }
                },
                {
                    field: 'fitedProbability',
                    title: '拟合概率计算值(p)',
                    width: '10%',
                    align: 'center',
                    editor: {type: 'numberbox', options: {precision: 5}},
                },
                {
                    field: 'correctedProbability',
                    title: '概率-修正值',
                    width: '10%',
                    align: 'center',
                    formatter: function (value, rowData, rowIndex) {
                        var correctedProbability = new Number(value).toFixed(4);
                        return '<a href="#" onclick="_editFxEconomyLossProbabilityCompute(\'' + rowData.id + '\', \'correctedProbability\');"> ' + correctedProbability + ' </a> '
                    }
                },
                {
                    field: 'economicLoss',
                    title: '经济损失-计算（万元）',
                    width: '11%',
                    align: 'center',
                },
                {
                    field: 'expectation',
                    title: '期望',
                    width: '10%',
                    align: 'center',
                },
                {
                    field: 'correctedExpectation',
                    title: '期望-修正值',
                    width: '10%',
                    align: 'center',
                    formatter: function (value, rowData, rowIndex) {
                        var correctedExpectation = new Number(value).toFixed(2);
                        return '<a href="#" onclick="_editFxEconomyLossProbabilityCompute(\'' + rowData.id + '\', \'correctedExpectation\');"> ' + correctedExpectation + ' </a> '
                    }
                },
            ]],
            toolbar: [/*{
                iconCls: 'fa fa-plus-circle',
                text:"添加",
                handler: function(){
                    addFxEconomyLossProbabilityCompute();
                }
            },*/ {
                iconCls: 'fa fa-plus-circle',
                text: "模板",
                handler: function () {
                    exportFxEconomyLossProbabilityComputeTemplet();
                }
            }, {
                iconCls: 'fa fa-upload',
                text: "导入",
                handler: function () {
                    importFxEconomyLossProbabilityCompute();
                }
            }, {
                iconCls: 'fa fa-download',
                text: "导出",
                handler: function () {
                    exportFxEconomyLossProbabilityCompute();
                }
            }/*, {
                iconCls: 'fa fa-trash-o',
                text:"删除",
                handler: function(){
                    deleteFxEconomyLossProbabilityCompute();
                }
            }*/],
            queryParams: {
                province: $("#provinceSelect").find("option:selected").text(),
                city: $("#citySelect").find("option:selected").text(),
                area: $("#areaSelect").find("option:selected").text(),
            },
            onLoadSuccess: function (data) {
                //垂直合并单元格
                mergeCells("fxEconomyLossProbabilityComputeGrid", "province,city,area,expectation,correctedExpectation");
            },
            onClickCell: function (rowIndex, field, value) {
                //console.log("onClickCell: ", rowIndex, field, value);
                if (field == "fitedProbability") {
                    global_editedCell && $(global_editedCell["this"]).datagrid('endEdit', global_editedCell["rowIndex"]);
                    $(this).datagrid('beginEdit', rowIndex);
                    global_editedCell = {"this": this, "rowIndex": rowIndex};
                } else {
                    console.log('endEdit',);
                    global_editedCell && $(global_editedCell["this"]).datagrid('endEdit', global_editedCell["rowIndex"]);
                }
            },
            onAfterEdit: function (index, row, changes) {
                console.log("onAfterEdit: ", index, row, changes);
                var fp = changes.fitedProbability, yy = parseFloat(fp);
                yy = Math.log(yy);
                var v = (Math.log(global_K0) - yy) / global_K1;
                var xx = Math.pow(Math.E, v);
                console.log("xx: ", xx, " yy: ", yy);
                $("#fxEconomyLossProbabilityComputeGrid").datagrid('getRows')[index]["fitedProbability"] = fp;
                $("#fxEconomyLossProbabilityComputeGrid").datagrid('getRows')[index]["economicLoss"] = xx.toFixed(4);

                var rowsData = $("#fxEconomyLossProbabilityComputeGrid").datagrid('getData').rows,
                    economicLossExpectation = 0;
                for (let i = 0; i < rowsData.length; i++) {
                    economicLossExpectation += rowsData[i].correctedProbability * rowsData[i].economicLoss;
                }
                //console.log("economicLossExpectation: ", economicLossExpectation);
                for (let i = 0; i < rowsData.length; i++) {
                    $("#fxEconomyLossProbabilityComputeGrid").datagrid('getRows')[i]["expectation"] = economicLossExpectation.toFixed(4);
                    $("#fxEconomyLossProbabilityComputeGrid").datagrid('refreshRow', i);
                }
                mergeCells("fxEconomyLossProbabilityComputeGrid", "province,city,area,expectation,correctedExpectation");
            },
            /*pagination: true,
            pageSize: 10*/
        });
    };

    var global_editedCell;
    $.extend($.fn.datagrid.defaults.editors, {
        text: {
            init: function (container, options) {
                var input = $('<input type="text" class="datagrid-editable-input">').appendTo(container);
                return input;
            },
            getValue: function (target) {
                return $(target).val();
            },
            setValue: function (target, value) {
                $(target).val(value);
            },
            resize: function (target, width) {
                var input = $(target);
                if ($.boxModel == true) {
                    input.width(width - (input.outerWidth() - input.width()));
                } else {
                    input.width(width);
                }
            }
        }
    });
    function mergeCells(tableID, colList) {
        var colArray = colList.split(",");
        var tTable = $("#" + tableID);
        var tableRows = tTable.datagrid("getRows");
        var tableRowCnts = tableRows.length;
        var rowspan;
        var preTxt = "";
        var curTxt = "";
        for (j = colArray.length - 1; j >= 0; j--) {
            preTxt = "";
            rowspan = 1;
            for (i = 0; i <= tableRowCnts; i++) {
                if (i == tableRowCnts) {
                    curTxt = "";
                } else {
                    curTxt = tableRows[i][colArray[j]];
                }
                if (preTxt == curTxt) {
                    rowspan += 1;
                } else {
                    tTable.datagrid("mergeCells", {
                        index: i - rowspan,
                        field: colArray[j],//合并字段
                        rowspan: rowspan,
                        colspan: null
                    });
                    rowspan = 1;
                }
                preTxt = curTxt;
            }
        }
    };

    var formValidator = function () {
        $("#fxEconomyLossProbabilityComputeForm").validate({
            rules: {
                fitedProbability: {
                    required: true,
                },
                correctedProbability: {
                    required: true,
                },
            },
            messages: {
                fitedProbability: {
                    required: "拟合概率计算值(p)不允许为空!",
                },
                correctedProbability: {
                    required: "概率-修正值不允许为空!",
                },
            }
        });
    };
    var getFxEconomyLossProbabilityCompute = function (id) {
        $.ajax({
            url: getFxEconomyLossProbabilityComputeController() + "/" + id,
            type: "get",
            success: function (data) {
                Tool.deserialize("fxEconomicLossProbabilityComputeForm", data);
            }
        });
    };

    window._editFxEconomyLossProbabilityCompute = function (fxEconomyLossProbabilityComputeId, field) {
        var slidebar = Util.slidebar({
            url: fxEconomyLossProbabilityComputeFormHtml,
            width: "580px",
            cache: false,
            close: true,
            afterLoad: function () {
                assistProbabilityCompute(field);
                formValidator();
                getFxEconomyLossProbabilityCompute(fxEconomyLossProbabilityComputeId);
                if (field == "correctedProbability") {
                    $("#saveBtn").on("click", function () {
                        if ($("#fxEconomicLossProbabilityComputeForm").valid()) {
                            var data = Tool.serialize("fxEconomicLossProbabilityComputeForm");
                            $.ajax({
                                url: getFxEconomyLossProbabilityComputeController(),
                                contentType: "application/json",
                                data: JSON.stringify(data),
                                type: "put",
                                success: function (data) {
                                    Util.alert(data.message);
                                    slidebar.close();
                                    createFxEconomyLossProbabilityComputeGrid();
                                }
                            });
                        }
                    });
                } else if (field == "correctedExpectation") {
                    $("#saveBtn").on("click", function () {
                        if ($("#fxEconomicLossProbabilityComputeForm").valid()) {
                            var val = $("#correctedExpectation").val();
                            var rowsData = $("#fxEconomyLossProbabilityComputeGrid").datagrid('getData').rows;
                            for (let i = 0; i < rowsData.length; i++) {
                                rowsData[i].correctedExpectation = val;
                                $.ajax({
                                    url: getFxEconomyLossProbabilityComputeController(),
                                    contentType: "application/json",
                                    data: JSON.stringify(rowsData[i]),
                                    type: "put",
                                    success: function (data) {
                                        (i == rowsData.length - 1) && (createFxEconomyLossProbabilityComputeGrid(), slidebar.close(), Util.alert(data.message));
                                    }
                                });
                            }
                        }
                    });
                }
            }
        });
    };
    var assistProbabilityCompute = function (field) {
        var cProbability = $("#correctedProbability").parent().parent().parent(),
            cExpectation = $("#correctedExpectation").parent().parent().parent();
        if (field == "correctedProbability") {
            cProbability.show();
            cExpectation.hide();
        } else if (field == "correctedExpectation") {
            cProbability.hide();
            cExpectation.show();
        }
    };

    var exportFxEconomyLossProbabilityComputeTemplet = function () {
        window.location.href = getServer() + "/excel/经济损失风险评估-概率性损失区划模板.xlsx";
    }
    var exportFxEconomyLossProbabilityCompute = function () {
        let province = $("#provinceSelect").val(), city = $("#citySelect").val(), area = $("#areaSelect").val();
        window.location.href = getFxEconomyLossProbabilityComputeController() + "/export?province=" + province + "&city=" + city + "&area=" + area;
    };
    var importFxEconomyLossProbabilityCompute = function () {
        // 模板下载
        $("#uploadModal").modal();
        $("#uploadModal").on("shown.bs.modal", function () {
            var url = getServer() + "/excel/经济损失风险评估-概率性损失区划模板.xlsx";
            $("#downloadZwExcelTemplate").attr("href", url);
        });

        $('#uploadButton').off("click");
        $("#uploadButton").on("click", function () {
            var uploadinput = document.getElementById("uploadFile");
            if (uploadinput.value == "") {
                Util.alert("上传前请先选择文件!");
                return;
            }
            var formData = new FormData();
            formData.append("file", uploadinput.files[0]);
            $.ajax({
                url: getFxEconomyLossProbabilityComputeController() + "/import",
                data: formData,
                processData: false, //因为data值是FormData对象，不需要对数据做处理。
                contentType: false,
                type: "POST",
                success: function (data) {
                    $('#uploadModal').modal('hide');
                    uploadinput.value = null;
                    Util.alert(data);
                }
            });
        });
    };

    return {
        init: init
    };
});
